// services/bluetooth.service.ts

interface BluetoothDevice {
  deviceId: string;
  name: string;
  RSSI?: number;
  localName?: string;
  advertisData?: ArrayBuffer;
  serviceUUIDs?: string[];
}

class BluetoothService {
  private foundDevices: BluetoothDevice[] = [];
  
  // 初始化蓝牙适配器
  async init(): Promise<boolean> {
    try {
      await uni.openBluetoothAdapter();
      console.log('蓝牙适配器初始化成功');
      return true;
    } catch (error) {
      console.error('蓝牙适配器初始化失败', error);
      uni.showToast({
        title: '请确保蓝牙已打开',
        icon: 'none'
      });
      return false;
    }
  }
  
  // 开始搜索蓝牙设备
  async startDiscovery(): Promise<boolean> {
    try {
      uni.startBluetoothDevicesDiscovery({
			allowDuplicatesKey: false,
			success: () => {
				uni.onBluetoothDeviceFound(this.handleDeviceFound.bind(this));
				console.log('开始搜索蓝牙设备');
			}
		});
      return true;
    } catch (error) {
      console.error('开始搜索失败', error);
      return false;
    }
  }
  
  // 处理找到的新设备
  private handleDeviceFound(res: { devices: BluetoothDevice[] }) {
    res.devices.forEach(device => {
      if (!this.foundDevices.some(d => d.deviceId === device.deviceId)) {
        this.foundDevices.push(device);
        console.log('找到新设备:', device);
      }
    });
  }
  
  // 重新初始化并搜索蓝牙设备
  async reInitAndDiscover(): Promise<boolean> {
    try {
      // 1. 停止当前搜索
      await this.stopDiscovery();
      
      // 2. 关闭蓝牙适配器
      await this.closeBluetoothAdapter();
      
      // 3. 清空设备列表
      this.foundDevices = [];
      
      // 4. 重新初始化蓝牙适配器
      const initSuccess = await this.init();
      if (!initSuccess) {
        return false;
      }
      
      // 5. 开始新的搜索
      return await this.startDiscovery();
    } catch (error) {
      console.error('重新初始化并搜索失败', error);
      return false;
    }
  }
  
  // 停止搜索蓝牙设备
  async stopDiscovery(): Promise<boolean> {
    try {
      await uni.stopBluetoothDevicesDiscovery();
      uni.offBluetoothDeviceFound();
      console.log('停止搜索蓝牙设备');
      return true;
    } catch (error) {
      console.error('停止搜索失败', error);
      return false;
    }
  }
  
  // 关闭蓝牙适配器
  async closeBluetoothAdapter(): Promise<boolean> {
    try {
      await uni.closeBluetoothAdapter();
      console.log('蓝牙适配器已关闭');
      return true;
    } catch (error) {
      console.error('关闭蓝牙适配器失败', error);
      return false;
    }
  }
  
  // 获取已找到的设备
  getFoundDevices(): BluetoothDevice[] {
    return [...this.foundDevices];
  }
}

export default new BluetoothService();